package com.polidea.rxohosble2.sample.example1a_background_scanning;


import com.polidea.rxohosble2.RxBleClient;
import com.polidea.rxohosble2.exceptions.BleScanException;
import com.polidea.rxohosble2.internal.RxBleLog;
import com.polidea.rxohosble2.sample.ResourceTable;
import com.polidea.rxohosble2.sample.SampleApplication;
import com.polidea.rxohosble2.sample.util.LocationPermission;
import com.polidea.rxohosble2.sample.util.ScanExceptionHandler;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.bundle.IBundleManager;
import ohos.event.commonevent.CommonEventManager;
import ohos.event.commonevent.CommonEventSubscribeInfo;
import ohos.event.commonevent.CommonEventSupport;
import ohos.event.commonevent.MatchingSkills;
import ohos.rpc.RemoteException;

public class BackgroundScanAbility extends Ability {
    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 10002;
    private static final int SCAN_REQUEST_CODE = 42;
    private RxBleClient rxBleClient;
    private Intent callbackIntent;
    private boolean hasClickedScan;
    ScanReceiver subscriber;
    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setPattern(ResourceTable.Pattern_base);
        super.setUIContent(ResourceTable.Layout_ability_example1a);
        findComponentById(ResourceTable.Id_scan_start_btn).setClickedListener(this::onScanStartClick);
        findComponentById(ResourceTable.Id_scan_stop_btn).setClickedListener(this::onScanStopClick);
        rxBleClient = SampleApplication.getRxBleClient(this);
        callbackIntent = new Intent();
        registerReceiver();
    }

    public void onScanStartClick(Component component) {
        hasClickedScan = true;
        if (rxBleClient.isScanRuntimePermissionGranted()) {

            scanBleDeviceInBackground();
        } else {
            LocationPermission.requestLocationPermission(null, null);
        }
    }

    private void scanBleDeviceInBackground() {
            try {
                rxBleClient.getBackgroundScanner().scanBleDeviceInBackground(
                        callbackIntent,
                        null
                );
            } catch (BleScanException scanException) {
                RxBleLog.w("BackgroundScanActivity, Failed to start background scan");
                ScanExceptionHandler.handleException(this, scanException);
            }

    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // 匹配requestPermissions的requestCode
                if (grantResults.length > 0
                        && grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
                    // 权限被授予
                    // 注意：因时间差导致接口权限检查时有无权限，所以对那些因无权限而抛异常的接口进行异常捕获处理
                    if (LocationPermission.isRequestLocationPermissionGranted(requestCode, permissions, grantResults, rxBleClient)
                            && hasClickedScan) {
                        hasClickedScan = false;
                        scanBleDeviceInBackground();
                    }
                } else {
                    // 权限被拒绝
                }
                return;
            }
        }
    }

    public void onScanStopClick(Component component) {
        rxBleClient.getBackgroundScanner().stopBackgroundBleScan(callbackIntent);
    }


    private void registerReceiver() {
        String event = "com.polidea.rxohosble2";
        MatchingSkills matchingSkills = new MatchingSkills();
        matchingSkills.addEvent(event); // 自定义事件
        matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_SCREEN_ON); // 亮屏事件
        CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
        subscriber = new ScanReceiver(subscribeInfo);
        try {
            CommonEventManager.subscribeCommonEvent(subscriber);
        } catch (RemoteException e) {
            RxBleLog.e("Exception occurred during subscribeCommonEvent invocation.");
        }
    }

    private void unregisterReceiver() {
        if (subscriber != null) {
            try {
                CommonEventManager.unsubscribeCommonEvent(subscriber);
            } catch (RemoteException e) {
                RxBleLog.e("Exception occurred during unsubscribeCommonEvent invocation.");
            }
            subscriber = null;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver();
    }
}
